package io.renren.modules.iots.test.socket.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;


/**
 * Socket的管理工具类
 * @author zhouxidong
 */
public class SocketManager {
	
	private String serverIP;
	private int serverPORT;
	private SocketChannel channel = null;
	
	public SocketManager(String serverIP,int serverPORT){
		this.serverIP = serverIP;
		this.serverPORT = serverPORT;
		getChannel();
	}
	
	
	/**
	 * 主动链接客户端
	 * @param serverIP
	 * @param serverPORT
	 * @return
	 */
	public boolean connect(String serverIP,int serverPORT){
		try {
			new TCPClient(serverIP,serverPORT);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 获取通道
	 */
	private void getChannel(){
//		channel = SocketUtils.SOCKETMANAGER.get(serverIP+":"+serverPORT);
	}
	
	/**
	 * 向服务端发信息(写数据)
	 * @param msg
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public boolean writeMsg(String msg) throws UnsupportedEncodingException{
		ByteBuffer writeBuffer = ByteBuffer.wrap(msg.getBytes("UTF-8"));
		try {
			channel.write(writeBuffer);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
